package net.kazed.nextaction.task;

import net.kazed.nextaction.ApplicationResource;
import net.kazed.nextaction.NextActionApplication;
import net.kazed.nextaction.R;
import net.kazed.nextaction.context.activity.TaskListItemView;
import net.kazed.nextaction.database.GtdContext;
import net.kazed.nextaction.database.Task;
import android.app.ListActivity;
import android.content.ContentUris;
import android.content.ContentValues;
import android.content.Context;
import android.content.Intent;
import android.content.res.Resources;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ListView;
import android.widget.SimpleCursorAdapter;

public class TaskSubTasksViewActivity extends ListActivity {

    private static final String cTag = "ActionViewActivity";
    
    private static final int MENU_ADD_SUB_TASK = Menu.FIRST;
   
    private static final int ACTION_NEW_SUB_TASK = 1;
    private static final int ACTION_VIEW_TASK = 2;
    
    private Cursor subTaskCursor;
    private Uri itemUri;
    private long taskId;
    
    private ApplicationResource applicationResource;
        
    @Override
    protected void onCreate(Bundle icicle) {
        super.onCreate(icicle);
        
        setContentView(R.layout.task_sub_tasks_view);
        setDefaultKeyMode(DEFAULT_KEYS_SHORTCUT);
        
        itemUri = getIntent().getData();
        taskId = ContentUris.parseId(itemUri);
        
        NextActionApplication application = (NextActionApplication) getApplication();
        applicationResource = application.getApplicationResource();

        subTaskCursor = managedQuery(Task.CONTENT_URI, Task.FULL_PROJECTION.getFieldNames(),
                        Task.Column.PARENT_TASK_ID + "=?", new String[] {Long.toString(taskId)}, Task.SORT_ORDER);
        setListAdapter(new SubTaskListAdapter(this, R.layout.list_item_view, subTaskCursor));
    }
    
    @Override
    protected void onResume() {
        super.onResume();
    }

    @Override
    protected void onListItemClick(ListView l, View v, int position, long id) {
        Uri itemUri = ContentUris.withAppendedId(Task.CONTENT_URI, id);
        String action = getIntent().getAction();
        if (Intent.ACTION_PICK.equals(action) || Intent.ACTION_GET_CONTENT.equals(action)) {
            Intent intent = new Intent(Intent.ACTION_PICK, itemUri);
            setResult(RESULT_OK, intent);
        } else {
            Intent intent = new Intent(Intent.ACTION_VIEW, itemUri);
            startActivityForResult(intent, ACTION_VIEW_TASK);
        }
    }

    @Override
	protected void onActivityResult(int requestCode, int resultCode,
			Intent data) {
    	Log.d(cTag, "Got resultCode " + resultCode + " with data " + data);		
	}
        
    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
       Resources resources = getResources();
       menu.add(0, MENU_ADD_SUB_TASK, 0, resources.getString(R.string.menu_add_sub_task))
       .setIcon(android.R.drawable.ic_menu_add).setAlphabeticShortcut('s');
       return super.onCreateOptionsMenu(menu);
    }
    
    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
       switch (item.getItemId()) {
       case MENU_ADD_SUB_TASK:
           Task task = getTask();
           Task subTask = new Task(null, null, task.getContextId(), (int) taskId, null, null, null, null, null, false, null);
           ContentValues values = new ContentValues();
           subTask.toValues(values);
           Uri newSubTaskItemUri = getContentResolver().insert(Task.CONTENT_URI, values);
           Intent subTaskIntent = new Intent(Intent.ACTION_INSERT, newSubTaskItemUri);
           if (task != null) {
               subTaskIntent.putExtra(GtdContext.SELECTED_CONTEXT_ID, task.getContextId());
           }

           startActivityForResult(subTaskIntent, ACTION_NEW_SUB_TASK);
          break;
       }
       return super.onOptionsItemSelected(item);
    }
    
    private Task getTask() {
        Task task = null;
        Cursor cursor = managedQuery(itemUri, Task.FULL_PROJECTION.getFieldNames(), null, null, null);
        if (cursor.moveToFirst()) {
            task = new Task(cursor);
        }
        cursor.close();
        return task;
    }
    
    private class SubTaskListAdapter extends SimpleCursorAdapter {
        
        private static final String cTag = "SubTaskListAdapter";

        public SubTaskListAdapter(Context context, int listItemLayoutId, Cursor cursor) {
           super(context, listItemLayoutId, cursor, new String[] { Task.Column.DESCRIPTION },
                    new int[] { R.id.description });
        }
        
        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
           Log.d(cTag, "getView position=" + position + ". Old view=" + convertView);
           TaskListItemView taskView = null;
           if (convertView instanceof TaskListItemView) {
               taskView = (TaskListItemView) convertView;
           } else {
               taskView = new TaskListItemView(parent.getContext(), applicationResource);
           }
           Cursor cursor = getCursor();
           if (cursor.moveToPosition(position)) {
               Task task = new Task(cursor);
               taskView.updateView(task);
           }
           return taskView;
        }

     }

}
